package com.example.message.handler;

import com.example.message.service.SysMessageService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;

public abstract class AbstractSysMessageHandler implements SysMessageHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${sitc.file.dir}")
    private String filePath;

    @Override
    public void send(String context) {
        String uuid = UUID.randomUUID().toString();
        File file = null;
        FileWriter fileWriter = null;
        try {
            file = new File(this.filePath + File.separatorChar + getName() + File.separatorChar + uuid);
            fileWriter = new FileWriter(file);
            fileWriter.write(context);
            FileUtils.copyFile(file, new File(this.filePath + File.separatorChar + SysMessageService.MESSAGES + File.separatorChar + uuid));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public String getFilePath() {
        return filePath;
    }
}
